package it.sm.myhome;

import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class CategoryTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout activitiesList = (LinearLayout) findViewById(R.id.activitiesList);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PackageManager pkgManager = getPackageManager();
        List<ResolveInfo> activities = pkgManager.queryIntentActivities(intent, 0);

        for (ResolveInfo resolveInfo : activities) {
        	final ResolveInfo ri = resolveInfo;
        	Button button = new Button(this); //Passo5: un bottone per app
        	button.setText(resolveInfo.loadLabel(pkgManager));
        	// Passo 7: associazione evento-view
        	button.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(); //Passo6: lancio intent
        			ComponentName cn = new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
        			intent.setComponent(cn);
        			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        			intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        			startActivity(intent);
				}
        	});
        	activitiesList.addView(button);
        }
    }
}